"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : reindex
Case Name   : 事务中执行reindex system concurrently报错
Create At   : 2022/08/30
Owner       : @zou_jialiang050
Description :
    1.新建数据库
    2.开启事务,执行reindex system concurrently
    3.清理环境
Expect      :
    1.成功
    2.合理报错
    3.成功
History     :
"""

import os
import unittest
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.dbuserNode = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.database = 'd_reindex_concurrency_0061'
        self.Constant = Constant()

    def test_reindex(self):
        step1 = 'step1:新建数据库 expect:成功'
        self.logger.info(step1)
        create_database = self.primary_sh.execut_db_sql(f'''
            drop database if exists {self.database};
            create database {self.database};''')
        self.logger.info(create_database)
        self.assertIn(self.Constant.CREATE_DATABASE_SUCCESS, create_database,
                      "建表失败" + step1)

        step2 = 'step2:开启事务,执行reindex system concurrently expect:合理报错'
        self.logger.info(step2)
        strat_transaction = self.primary_sh.execut_db_sql(
            f'''start transaction;
            reindex system concurrently {self.database};
            rollback;''')
        self.logger.info(strat_transaction)
        self.assertIn('ERROR:  REINDEX CONCURRENTLY cannot run inside a '
                      'transaction block', strat_transaction, '执行失败' + 
                      step2)

    def tearDown(self):
        step3 = 'step3:清理环境 expect:成功'
        self.logger.info(step3)
        clean_environment = self.primary_sh.execut_db_sql(
            f'''drop database {self.database};''')
        self.logger.info(clean_environment)
        self.assertIn(self.Constant.DROP_DATABASE_SUCCESS, clean_environment,
                      '执行失败' + step3)
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
